package com.bgy.common;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bgy.model.MeetingRoom;
import com.bgy.model.Meetingcreate;
import com.bgy.model.Mmsryxx;
import com.bgy.sms.MeetingNotice;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.qyweixin.sdk.api.ApiConfigKit;
import com.jfinal.qyweixin.sdk.api.ApiResult;
import com.jfinal.qyweixin.sdk.api.JsTicket;
import com.jfinal.qyweixin.sdk.api.JsTicketApi;
import com.jfinal.qyweixin.sdk.api.JsTicketApi.JsApiType;
import com.jfinal.qyweixin.sdk.api.OAuthApi;


public class QyIndexController extends Controller{
	
	public void index() {		
		renderText("这是我的测试页");
	}
	
	public void login(){
		//OAuthApi.getUserInfo();
//		Object userId = getSession().getAttribute("userId");
//		Object openId = getSession().getAttribute("openId");
	
		code();
	}
	
	public void code(){
		String userId =null;
		String deviceId=null;
		String openid=null;
		if (!isParaBlank("code")) {
			String code = getPara("code");
			//logger.info("code:"+code);
			if (!isParaBlank("state")) {
				String state = getPara("state");
				//logger.info(" state:"+state);
			}
			ApiResult userInfoApiResult = OAuthApi.getUserInfoByCode(code);
			if (userInfoApiResult.isSucceed()) {
				String userInfoJson=userInfoApiResult.getJson();
				JSONObject object = JSON.parseObject(userInfoJson);
				deviceId = object.getString("DeviceId");
				try {
					userId = object.getString("UserId"); //如果获取userId为空 说明没有关注					
					if (userId!=null && !userId.equals("")) {
						ApiResult toOpenIdApiResult = OAuthApi.ToOpenId("{\"userid\":\""+userId+"\",\"agentid\":0}");
						if (toOpenIdApiResult.isSucceed()) {
							openid=JSON.parseObject(toOpenIdApiResult.getJson()).getString("openid");
						}
					}else {
						openid = object.getString("OpenId");
						String json="{\"openid\":\""+openid+"\"}"; //如果未关注 openid无法转化为userid						
						ApiResult toUserIdApiResult = OAuthApi.ToUserId(json);
						if (toUserIdApiResult.isSucceed()) {
							userId=JSON.parseObject(toUserIdApiResult.getJson()).getString("userid");
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}			
			//renderText(userInfoApiResult.getJson()+">>>userId:"+userId+" deviceId:"+deviceId+" openid:"+openid);
			//setAttr("openID", "userId:"+userId+" deviceId:"+deviceId+" openid:"+openid);
			setAttr("test", "登录...openId>"+openid+" userId>"+userId);	
			//renderJsp("/view/huiyi.jsp");
			renderJsp("index.jsp");
		}
	}	
	
	//urlPara 是指没有名字只有位置，并且是在url存在的参数。
	public void meetingmain() {
		//render("meeting_main.html");
		System.out.println(getParaNames());
		String url="http://hecore.s1.natapp.cc/meetingmain";
		String nonce_str="测试";
		setAttr("nonceStr",nonce_str);	
		Timestamp ts = new Timestamp(System.currentTimeMillis()); 
		String timestamp=ts.toString();	
		JsTicket jsApiTicket = JsTicketApi.getTicket(JsApiType.jsapi);
		String jsapi_ticket = jsApiTicket.getTicket();							
		String[] paramArr = new String[] {"jsapi_ticket=" + jsapi_ticket, "noncestr=" + nonce_str, "timestamp=" + timestamp,"url=" + url };  
        Arrays.sort(paramArr); //将排序后的结果拼接成一个字符串           
        String content = paramArr[0].concat("&"+paramArr[1]).concat("&"+paramArr[2]).concat("&"+paramArr[3]);  
		String signature = HashKit.sha1(content);		
/*		String appid=PropKit.get("appId");//10002
		setAttr("appid",appid);*/
		String urlt = "http://" + getRequest().getServerName() + getRequest().getContextPath() + "/";
		System.out.println("我的:" + urlt);		
		setAttr("appId", ApiConfigKit.getApiConfig().getCorpId());
		setAttr("nonceStr", nonce_str);
		setAttr("timestamp", timestamp);
		setAttr("url", url);
		setAttr("signature", signature);	
		setAttr("timestamp",timestamp);				
		System.out.println("程序执行");	
//		Object userId = getSession().getAttribute("userId");
//		Object openId = getSession().getAttribute("openId");
//		setAttr("test", "这里是测试...openId>"+openId+" userId>"+userId);		
//		System.out.println("这里是测试...openId>"+openId+" userId>"+userId);
		render("meeting.jsp");
	}
	
	public void submit(){
		String name=getPara("name");
		//寫庫操作
		System.out.println("寫庫"+name);
	}
	
	public void meetingroom() {
		render("meetingroom.html");
	}
	
	/**
	 * 会议列表，待进行会议，已结束会议，已取消会议
	 */
	public void meetinglist() {
		String status = getPara("status");
		String openID = getPara("userid");
		if (StrKit.isBlank(status)){
			status = "0";
		}
		setAttr("status", status);
		setAttr("openID", openID);
		renderJsp("meeting_list.jsp");
	}	
	
	public void meetingdetail(){	
		setAttr("xh", getPara(0));	
		setAttr("appid", getPara(1));	
		setAttr("nonceStr", getPara(2));	
		setAttr("timestamp", getPara(3));	
		setAttr("gnonceStr", getPara(4));	
		setAttr("gtimestamp", getPara(5));	
		setAttr("gsignature", getPara(6));	
		setAttr("groupid", getPara(7));	
		setAttr("openID", getPara(8));	
		renderJsp("meeting_detail.jsp");
	}
	
	public void meetingroomlist(){
		render("meetingroom_list.html");
	}
	
	public void meetingroomdetail(){
		String xh = getPara(0);
		renderJsp("meetingroom_detail.jsp?xh=" + xh);
	}	

	public void getUsers(){		
		Page<Mmsryxx> pl = Mmsryxx.me.paginate(2, 20);
		String result = JsonKit.toJson(pl.getList());
		System.out.println(result);
		renderJson(result);
	}
	
	public void getMeetingRoom(){		
		List<MeetingRoom> pl = MeetingRoom.me.getAll();
		String result = JsonKit.toJson(pl);
		renderJson(result);
	}
	
	/**
	 * 获取单个会议室的详细信息
	 */
	public void getMeetingRoomInfo(){
		String xh = getPara("xh");
		MeetingRoom pl = MeetingRoom.me.findByXh(xh);
		String result = JsonKit.toJson(pl);
		renderJson(result);
	}
	
	/**
	 * 生成地址本标签，用于选择发起人，以及参与人
	 */
	public void getAddressList(){
		MeetingNotice mn = new MeetingNotice();
		String value = mn.getUserList();		
		renderHtml(value);
	}	
	
	/**
	 * 新建会议室预订单
	 */
	public void newmeeting(){
		//获取传递的参数，解析然后保存到数据库
		String Mname = getPara("Mname");
		String Mcontent = getPara("Mcontent");
		String starttime = getPara("starttime");
		String finishtime = getPara("finishtime");
		String Mplace = getPara("Mplace");
		String Mrequire = getPara("Mrequire");
		String Msponsor = getPara("Msponsor");
		String Mactor = getPara("Mactor");
		String fqr    = getPara("fqr");
		Meetingcreate me = new Meetingcreate();
		boolean r = me.save(Mname, Mcontent, starttime, finishtime, Mplace, Msponsor, Mactor,fqr,"","",Mrequire);		
		if (r){
			String url = "http://" + getRequest().getServerName() + getRequest().getContextPath() + "/";
			//System.out.println("我的:" + url);
			MeetingNotice mn = new MeetingNotice();
			mn.sendMXNotice(url);
			renderText("0");			
		}else{
			renderText("1");
		}
	}
	
	/**
	 * 获取三小时内会议室被占用的列表
	 * 前端 Ajax 进行调用
	 */
	public void getBusyMeetingRoom(){
		List<Meetingcreate> pl = Meetingcreate.me.getAllBusy();
		String result = JsonKit.toJson(pl);
		renderJson(result);
	}
	
	/**
	 * 获取会议列表
	 * 前端 Ajax 进行调用
	 * status=0,1,2,3 待进行会议，已结束会议，已取消会议，已删除会议
	 * @param flag
	 */
	public void getMeetingList(){
		String status = getPara("status");
		if (StrKit.isBlank(status)){
			status = "0";
		}
		List<Meetingcreate> pl = Meetingcreate.me.getAll(status);
		String result = JsonKit.toJson(pl);
		renderJson(result);
	}
	
	/**
	 * 获取单个会议的详细信息
	 */
	public void getMeetingDetailInfo(){
		String xh = getPara("xh");
		Meetingcreate pl = Meetingcreate.me.findByXh(xh);
		MeetingNotice mn = new MeetingNotice(); 
		List<Map<String,String>> ls_zcr = getUserList(pl.getStr("zcr"),mn);
		List<Map<String,String>> ls_chr = getUserList(pl.getStr("chr"),mn);
		List<Map<String,String>> ls_fqr = getUserList(pl.getStr("fqr"),mn);		
		/*List<Map<String,String>> ls_zcr = getUserList(pl.getStr("zcr"));
		List<Map<String,String>> ls_chr = getUserList(pl.getStr("chr"));
		List<Map<String,String>> ls_fqr = getUserList(pl.getStr("fqr"));*/		
		Map<String,Object> mp = new HashMap<String,Object>();
		mp.put("name", pl.getStr("name"));
		mp.put("content",pl.getStr("content"));
		mp.put("place",pl.getStr("place"));
		mp.put("starttime",pl.getTimestamp("starttime").toString());
		mp.put("finishtime",pl.getTimestamp("finishtime").toString());
		mp.put("optime",pl.getTimestamp("optime").toString());
		
		System.out.println(pl.getTimestamp("optime"));
		
		mp.put("status", String.valueOf(pl.getLong("status")));
		mp.put("zcr", ls_zcr);
		mp.put("chr", ls_chr);
		mp.put("fqr", ls_fqr);		
		String result = JSON.toJSONString(mp);
		renderJson(result);				
	}
	
	/**
	 * 获取用户信息
	 * @param userids  以逗号分割的userid  hegx,liha,duis,ddd
	 * @return
	 */
	/*private List<Map<String,String>> _getUserList(String userids){		
		List<Map<String,String>> lsmp = new ArrayList<Map<String,String>>();
		if (StringUtils.isBlank(userids)){
			return lsmp;
		}
		if ("@all".equals(userids)){
			Map<String,String> mp = new HashMap<String,String>();
			mp.put("userid", "@all");
			mp.put("name","所有人");
			mp.put("header","img/all_users.jpg");
			lsmp.add(mp);
			return lsmp;
		}
		String[] userls = userids.split(",");
		for (String userid:userls){
			Mmsryxx jsonUser = Mmsryxx.me.findByUserid(userid);
			if (jsonUser != null){
				Map<String,String> mp = new HashMap<String,String>();
				mp.put("userid", userid);
				mp.put("name",jsonUser.getStr("name"));
				mp.put("header",jsonUser.getStr("avatar"));
				lsmp.add(mp);
			}			
		}
		return lsmp;
	}*/
	
	/**
	 * 获取用户信息
	 * @param userids  以逗号分割的userid  hegx,liha,duis,ddd
	 * @return
	 */
	private List<Map<String,String>> getUserList(String userids,MeetingNotice mn){		
		List<Map<String,String>> lsmp = new ArrayList<Map<String,String>>();
		if (StringUtils.isBlank(userids)){
			return lsmp;
		}
		if ("@all".equals(userids)){
			Map<String,String> mp = new HashMap<String,String>();
			mp.put("userid", "@all");
			mp.put("name","所有人");
			mp.put("header","img/all_users.jpg");
			lsmp.add(mp);
			return lsmp;
		}
		String[] userls = userids.split(",");
		for (String userid:userls){
			String jsonss = mn.getUserInfo(userid);			
			JSONObject jsonUser = JSONObject.parseObject(jsonss);
			Map<String,String> mp = new HashMap<String,String>();
			mp.put("userid", userid);
			mp.put("name",jsonUser.getString("name"));
			mp.put("header",jsonUser.getString("avatar"));
			lsmp.add(mp);
		}
		return lsmp;
	}
	
	/**
	 * 获取会议状态发起人列表
	 */
	public void getFqrList(){
		String xh = getPara("xh");
		List<Meetingcreate> pl = Meetingcreate.me.getFqr(xh);
		JSONArray jsonArray = JSONArray.parseArray(JsonKit.toJson(pl));
		MeetingNotice mn = new MeetingNotice();
		List<Map<String,String>> lsmp = new ArrayList<Map<String,String>>();
		for(int k=0;k<jsonArray.size();k++){  
			JSONObject jsonObj = JSONObject.parseObject(jsonArray.get(k).toString());
			String userid = jsonObj.get("fqr").toString();
			String starttime = jsonObj.getString("starttime");
			String finishtime = jsonObj.getString("finishtime");
			String jsonss = mn.getUserInfo(userid);	
			System.out.println(jsonss);
			JSONObject jsonUser = JSONObject.parseObject(jsonss);
			Map<String,String> mp = new HashMap<String,String>();
			mp.put("userid", userid);
			mp.put("starttime",starttime);
			mp.put("finishtime",finishtime);
			mp.put("name",jsonUser.getString("name"));
			mp.put("header",jsonUser.getString("avatar"));
						 
			if (jsonUser.get("department") != null){
				String departs = jsonUser.get("department").toString();
				
				String dnum = departs.substring(departs.lastIndexOf(",") + 1,departs.indexOf("]"));
				String depInfo = mn.getDepartmentInfo(dnum);
				
				JSONObject jsonDep   = JSONObject.parseObject(depInfo);
				JSONArray jsonArrDep = JSONArray.parseArray(jsonDep.getString("department"));
				jsonDep   = JSONObject.parseObject(jsonArrDep.get(0).toString());
				mp.put("department",jsonDep.getString("name"));
			}else{
				mp.put("department","");
			}
			lsmp.add(mp);
		}
		String result = JsonKit.toJson(lsmp);
		renderJson(result);
	}
	
	public void cancelMeeting(){
		String xh = getPara("xh");
		String status = getPara("status");
		int v = Meetingcreate.me.cancelMeeting(xh,status);
		renderText(String.valueOf(v));
	}
	
	/**
	 * 手动同步微信后台用户信息，到前端本地数据库里，主要是把头像或其他信息同步过来，
	 * 以后设成定期，或者通知修改 
	 * hegx 2016-10-10
	 */
	public void syncWeiXinUserToLocalDB(){
		MeetingNotice mn = new MeetingNotice();
		mn.setWeiXinUserToLocalDB();
		renderText("处理完毕了");
	}
}
